package exec;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description 给定两个 01 字符串 a 和 b ，请计算它们的和，并以二进制字符串的形式输出。输入为 非空 字符串且只包含数字 1 和 0。
 * @Date 2022/10/26 9:47
 * @Created by wangjun
 */
public class AddBinary {

    /**
     * 功能描述: 输入: a = "11", b = "10"
     * 输出: "101"
     *
     * @Param: [a, b]
     * @Return: java.lang.String
     */
    public static String addBinary(String a, String b) {
        int m = a.length(), n = b.length();
        StringBuilder stringBuilder = new StringBuilder();
        if (m < n) {
            for (int i = 0;i < n - m;i++){
                stringBuilder.append("0");
            }
            // jdk 11
//            stringBuilder.append("0".repeat(n - m));
            a = stringBuilder.append(a).toString();
        } else {
            for (int i = 0;i < m - n;i++){
                stringBuilder.append("0");
            }
            // jdk11
//            stringBuilder.append("0".repeat(m - n));
            b = stringBuilder.append(b).toString();
        }
        int length = Math.max(a.length(), b.length());
        int carry = 0;
        StringBuilder result = new StringBuilder();
        for (int i = length - 1; i >= 0; i--) {
            int ai = a.charAt(i) == '0' ? 0 : 1;
            int bi = b.charAt(i) == '0' ? 0 : 1;
            int sum = ai + bi + carry;
            result.append(sum % 2);
            carry = sum / 2;
        }
        if (carry == 1) {
            result.append(1);
        }
        return result.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(addBinary("1111", "1111"));
    }
}
